﻿using Aspose.Cells;
using Common.Models;
using Common.Utility;
using Common.Utility.AJ.Extension;
using Microsoft.WindowsAPICodePack.Dialogs;
using Newtonsoft.Json;
using NPOI.XSSF.UserModel;
using SUT.PrintEngine.Utils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;

namespace WeighingRecord.Views
{
    /// <summary>
    /// WeightListView.xaml 的交互逻辑
    /// </summary>
    public partial class WeightTotalView : UserControl
    {


        public string StatusBar { get; set; }
        public Dictionary<string, string> TemplateFieldDic { get; set; } = new Dictionary<string, string>();
        public AppSettingsSection AppSection { get; } = (AppSettingsSection)ConfigurationManager.OpenExeConfiguration("衡七管家.exe").GetSection("appSettings");
        public Worksheet Worksheet { get; }
        public string WeighingUnit { get; }
        public List<WeighingRecordModel> WList { get; private set; } //从数据库中查询出的原始称重记录列表
        public DataTable RecordDT { get; private set; } = new DataTable(); //经过转换的称重记录表格，用来显示到列表、导出到excel


        public WeightTotalView()
        {
            InitializeComponent();
            //初始化数据
            var before1 = DateTime.Now.Date.ToString("yyyy-MM-dd");
            var before2 = DateTime.Now.Date.AddDays(1).ToString("yyyy-MM-dd");

            RecordDT.Columns.Add(new DataColumn("统计时间"));
            RecordDT.Columns.Add(new DataColumn("总毛重"));
            RecordDT.Columns.Add(new DataColumn("总净重"));
            RecordDT.Columns.Add(new DataColumn("总车次"));
            RecordDT.Columns.Add(new DataColumn("称重记录"));
            RecordDT.Columns.Add(new DataColumn("销售过磅"));
            RecordDT.Columns.Add(new DataColumn("采购过磅"));

            WeighingUnit = AppSection.Settings["WeighingUnit"].Value;
            GetData(before1, before2, "当天");
        }
        public void TotalToday_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            setTotalStyle(0);
            var before1 = DateTime.Now.Date.ToString("yyyy-MM-dd");
            var before2 = DateTime.Now.Date.AddDays(1).AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss");
            GetData(before1, before2, "当天");
        }
        public void TotalWeek_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            setTotalStyle(1);

            var start = Common.Utility.DateHelper.GetStartDate(Common.Utility.DateTimeType.Week, DateTime.Now).Date.ToString("yyy-MM-dd HH:mm:ss");
            var end = Common.Utility.DateHelper.GetEndDate(Common.Utility.DateTimeType.Week, DateTime.Now).Date.AddDays(1).AddSeconds(-1).ToString("yyy-MM-dd HH:mm:ss");
            //var end = Common.Utility.DateHelper.GetEndDate(Common.Utility.DateTimeType.Week, DateTime.Now).Date.AddSeconds(-1).ToString("yyy-MM-dd HH:mm:ss");
            GetData(start, end, "当周");
        }
        public void TotalMonth_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            setTotalStyle(2);
            var start = Common.Utility.DateHelper.GetStartDate(Common.Utility.DateTimeType.Month, DateTime.Now).Date.ToString("yyy-MM-dd HH:mm:ss");
            var end = Common.Utility.DateHelper.GetEndDate(Common.Utility.DateTimeType.Month, DateTime.Now).Date.AddDays(1).AddSeconds(-1).ToString("yyy-MM-dd HH:mm:ss");
            GetData(start, end, "当月");
        }
        public void TotalYear_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            setTotalStyle(3);
            var start = Common.Utility.DateHelper.GetStartDate(Common.Utility.DateTimeType.Year, DateTime.Now).Date.ToString("yyy-MM-dd HH:mm:ss");
            var end = Common.Utility.DateHelper.GetEndDate(Common.Utility.DateTimeType.Year, DateTime.Now).Date.AddDays(1).AddSeconds(-1).ToString("yyy-MM-dd HH:mm:ss");
            GetData(start, end, "当年");
        }

        public void setTotalStyle(int index)
        {
            TotalToday.SetResourceReference(StyleProperty, "whiteStyle");
            TotalWeek.SetResourceReference(StyleProperty, "whiteStyle");
            TotalMonth.SetResourceReference(StyleProperty, "whiteStyle");
            TotalYear.SetResourceReference(StyleProperty, "whiteStyle");
            if (index == 0) TotalToday.SetResourceReference(StyleProperty, "yellowStyle");
            else if (index == 1) TotalWeek.SetResourceReference(StyleProperty, "yellowStyle");
            else if (index == 2) TotalMonth.SetResourceReference(StyleProperty, "yellowStyle");
            else if (index == 3) TotalYear.SetResourceReference(StyleProperty, "yellowStyle");
        }

        public void GetData(string beginDate, string endDate, string dateRange)
        {
            RecordDT.Rows.Clear();
            var before1 = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
            var before2 = DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss");

            var maxAbnormalData = SettingsHelper
                    .ZXWeighingRecordSettings.Settings["MaxAbnormalData"]?.Value.TryGetDecimal() ?? 100000m;

            //获取当前选择日期的统计值
            var zh = Common.Data.SQLDataAccess.GetTotal(beginDate, endDate,maxAbnormalData);
            //获取前一天的统计值
            var zh1 = Common.Data.SQLDataAccess.GetTotal(before1, before2, maxAbnormalData);
            //获取当前选择日期的统计值
            var xs = Common.Data.SQLDataAccess.GetCountByGblx(beginDate, endDate, "销售", maxAbnormalData);
            //获取前一天的统计值
            var xs1 = Common.Data.SQLDataAccess.GetCountByGblx(before1, before2, "销售", maxAbnormalData);
            //获取当前选择日期的统计值
            var cg = Common.Data.SQLDataAccess.GetCountByGblx(beginDate, endDate, "采购", maxAbnormalData);
            //获取前一天的统计值
            var cg1 = Common.Data.SQLDataAccess.GetCountByGblx(before1, before2, "采购", maxAbnormalData);

            zh = zh == null ? new Common.Models.WeighingRecordModel() : zh;
            zh1 = zh1 == null ? new Common.Models.WeighingRecordModel() : zh1;
            xs = xs == null ? new Common.Models.WeighingRecordModel() : xs;
            xs1 = xs1 == null ? new Common.Models.WeighingRecordModel() : xs1;
            cg = cg == null ? new Common.Models.WeighingRecordModel() : cg;
            cg1 = cg1 == null ? new Common.Models.WeighingRecordModel() : cg1;

            decimal outNum = 0;


            //this.mz.Content = string.IsNullOrEmpty(zh.Mz) ? "0" : zh.Mz;
            //this.mz_1.Content = string.IsNullOrEmpty(zh1.Mz) ? "0" : zh1.Mz;
            //this.jz.Content = string.IsNullOrEmpty(zh.Jz) ? "0" : zh.Jz;
            //this.jz_1.Content = string.IsNullOrEmpty(zh1.Jz) ? "0" : zh1.Jz;
            decimal.TryParse(zh.Mz, out outNum);
            this.mz.Content = outNum.ToString("0.##");

            outNum = 0;
            decimal.TryParse(zh1.Mz, out outNum);
            this.mz_1.Content = outNum.ToString("0.##");

            outNum = 0;
            decimal.TryParse(zh.Jz, out outNum);
            this.jz.Content = outNum.ToString("0.##");

            outNum = 0;
            decimal.TryParse(zh1.Jz, out outNum);
            this.jz_1.Content = outNum.ToString("0.##");

            this.cc.Content = string.IsNullOrEmpty(zh.By1) ? "0" : zh.By1;
            this.cc_1.Content = string.IsNullOrEmpty(zh1.By1) ? "0" : zh1.By1;
            this.cjjl.Content = string.IsNullOrEmpty(zh.By2) ? "0" : zh.By2;
            this.cjjl_1.Content = string.IsNullOrEmpty(zh1.By2) ? "0" : zh1.By2;
            this.gblx1.Content = string.IsNullOrEmpty(xs.Gblx) ? "0" : xs.Gblx;
            this.gblx1_1.Content = string.IsNullOrEmpty(xs1.Gblx) ? "0" : xs1.Gblx;
            this.gblx2.Content = string.IsNullOrEmpty(cg.Gblx) ? "0" : cg.Gblx;
            this.gblx2_1.Content = string.IsNullOrEmpty(cg1.Gblx) ? "0" : cg1.Gblx;



            var unit = Common.Utility.SettingsHelper.AWSV2Settings.Settings["WeighingUnit"].Value;
            this.mz.Content += unit;
            this.mz_1.Content += unit;
            this.jz.Content += unit;
            this.jz_1.Content += unit;
            this.cc.Content += "次";
            this.cc_1.Content += "次";
            this.cjjl.Content += "条";
            this.cjjl_1.Content += "条";
            this.gblx1.Content += "条";
            this.gblx1_1.Content += "条";
            this.gblx2.Content += "条";
            this.gblx2_1.Content += "条";

            DataRow dr = RecordDT.NewRow();
            dr["统计时间"] = dateRange;
            dr["总毛重"] = this.mz.Content;
            dr["总净重"] = this.jz.Content;
            dr["总车次"] = this.cc.Content;
            dr["称重记录"] = this.cjjl.Content;
            dr["销售过磅"] = this.gblx1.Content;
            dr["采购过磅"] = this.gblx2.Content;
            RecordDT.Rows.Add(dr);

            DataRow dr1 = RecordDT.NewRow();
            dr1["统计时间"] = "前一天";
            dr1["总毛重"] = this.mz_1.Content;
            dr1["总净重"] = this.jz_1.Content;
            dr1["总车次"] = this.cc_1.Content;
            dr1["称重记录"] = this.cjjl_1.Content;
            dr1["销售过磅"] = this.gblx1_1.Content;
            dr1["采购过磅"] = this.gblx2_1.Content;
            RecordDT.Rows.Add(dr1);
        }


        public void PrintReport()
        {
            if (RecordDT == null)
            {
                StatusBar = "当前统计列表为空";
                return;
            }

            //设置列宽
            var columnWidths = new List<double>();
            for (int i = 0; i < RecordDT.Columns.Count; i++)
            {
                double columnWidth = 70;
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_kh"].Value)
                {
                    columnWidth = 80;
                }
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_ch"].Value)
                {
                    columnWidth = 80;
                }
                columnWidths.Add(columnWidth);
            }

            var ht = new AccountHeaderTemplate();
            var headerTemplate = XamlWriter.Save(ht);

            //headerTemplate = headerTemplate.Replace("@StartDate", ((DateTime)StartDate).ToString("yyyy/MM/dd")).Replace("@EndDate", ((DateTime)EndDate).ToString("yyyy/MM/dd"));
            headerTemplate = headerTemplate.Replace("@StartDate", DateTime.Now.ToString("yyyy/MM/dd")).Replace("@EndDate", "").Replace(" ~ ", "");
            headerTemplate = headerTemplate.Replace("@WeighingUnit", WeighingUnit);

            var printControl = PrintControlFactory.Create(RecordDT, columnWidths, headerTemplate);
            printControl.ShowPrintPreview();
        }

        public void ExportReport()
        {
            try
            {
                if (RecordDT == null)
                {
                    StatusBar = "当前统计列表为空";
                    return;
                }

                //使用DataTable数据新建excle表格
                Workbook workbook = new Workbook();
                Worksheet worksheet = workbook.Worksheets[0];
                worksheet.Name = "称重统计";

                ImportTableOptions importOptions = new ImportTableOptions();
                importOptions.IsFieldNameShown = true;
                importOptions.IsHtmlString = true;

                worksheet.Cells.ImportData(RecordDT, 0, 0, importOptions);

                #region 增加表头、格式

                Style blodStyle = workbook.CreateStyle();
                blodStyle.Font.IsBold = true;
                StyleFlag flag = new StyleFlag();
                flag.FontBold = true;

                Style headerStyle = workbook.CreateStyle();
                headerStyle.Font.IsBold = true;
                headerStyle.Font.Size = 16;
                headerStyle.HorizontalAlignment = TextAlignmentType.Center;

                worksheet.Cells.Rows[0].ApplyStyle(blodStyle, flag);

                worksheet.Cells.InsertRows(0, 3);

                worksheet.Cells.Merge(0, 0, 1, 8);
                worksheet.Cells["A1"].PutValue("称重统计表");
                worksheet.Cells["A1"].SetStyle(headerStyle);
                worksheet.Cells["A2"].PutValue("统计日期");
                worksheet.Cells["A2"].SetStyle(blodStyle);
                worksheet.Cells.Merge(1, 1, 1, 5);
                worksheet.Cells["B2"].PutValue(DateTime.Now.ToString("yyyy/MM/dd"));
                //worksheet.Cells["B2"].PutValue(((DateTime)StartDate).ToString("yyyy/MM/dd") + " ~ " + ((DateTime)EndDate).ToString("yyyy/MM/dd"));
                worksheet.Cells["G2"].PutValue("重量单位");
                worksheet.Cells["G2"].SetStyle(blodStyle);
                worksheet.Cells["H2"].PutValue(WeighingUnit);

                worksheet.AutoFitColumns();
                #endregion

                workbook.Save(Globalspace._weighingRecordTempPath, SaveFormat.Xlsx);

                //删掉aspose的试用版信息，删掉临时文件
                XSSFWorkbook book;
                using (FileStream file = new FileStream(Globalspace._weighingRecordTempPath, FileMode.Open, FileAccess.Read))
                {
                    book = new XSSFWorkbook(file);
                }
                //book.RemoveSheetAt(1);
                File.Delete(Globalspace._weighingRecordTempPath);

                //打开保存文件对话框，保存称重记录
                CommonSaveFileDialog dialog = new CommonSaveFileDialog();
                dialog.DefaultFileName = "称重统计_" + DateTime.Now.ToString("yyyyMMdd");
                dialog.DefaultExtension = "xlsx";
                dialog.AlwaysAppendDefaultExtension = true;
                dialog.Filters.Add(new CommonFileDialogFilter("Excel 工作簿", ".xlsx"));

                if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    FileStream file = new FileStream(dialog.FileName, FileMode.Create);
                    book.Write(file);
                    file.Close();
                    book.Close();
                    StatusBar = "导出成功！称重统计文件路径：" + dialog.FileName;
                }
            }
            catch (Exception e)
            {
                //log.Info($"ExportReport error:{e.Message}");
            }
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            PrintReport();
        }

        private void Button_Click_1(object sender, System.Windows.RoutedEventArgs e)
        {
            ExportReport();
        }
    }
}
